<template>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="行程编号">
            <el-input v-model="searchForm.tripNumber" placeholder="行程编号" clearable />
        </el-form-item>
        <el-form-item label="起始地">
            <el-input v-model="searchForm.start" placeholder="起始地" clearable />
        </el-form-item>
        <el-form-item label="目的地">
            <el-input v-model="searchForm.end" placeholder="目的地" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="GetTripList">查询</el-button>
        </el-form-item>
        <el-form-item>
            <el-button type="success" @click="addTrip">新增</el-button>
        </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%" height="120%">
        <el-table-column fixed prop="tripNumber" label="行程编号" width="135" />
        <el-table-column prop="start" label="起始地" width="165" />
        <el-table-column prop="end" label="目的地" width="165" />
        <el-table-column prop="type" label="类型" width="130">
            <template #default="scope">
                <span :style="{ color: getStatusLabel(scope.row.type).color }">
                    {{ getStatusLabel(scope.row.type).label }}
                </span>
            </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="125" />
        <el-table-column prop="vehiclesNumber" label="车辆数量" width="130" />
        <el-table-column prop="founderDate" label="创建时间" width="140" />
        <el-table-column prop="modifierDate" label="修改时间" width="140" />
        <el-table-column label="操作" fixed="right">
            <template #default="scope">
                <el-button type="warning" circle :icon="Edit" @click="updateTripList(scope.row.id)">
                </el-button>
                <el-button type="danger" circle :icon="Delete" @click="deleteTripList(scope.row.id)">
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
        <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[6, 12, 18, 25]"
            :size="size" :disabled="disabled" :background="background" layout="->, total, sizes, prev, pager, next"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <el-drawer v-model="dialog" title="行程修改" direction="rtl" class="demo-drawer">
        <div class="demo-drawer__content">
            <el-form :model="form">
                <el-form-item label="行程编号" :label-width="formLabelWidth">
                    <el-input v-model="form.tripNumber" autocomplete="off" />
                </el-form-item>
                <el-form-item label="起始地" :label-width="formLabelWidth">
                    <el-select v-model="form.start" placeholder="起始地" clearable>
                        <el-option v-for="status in StartList" :key="status.id" :label="status.start"
                            :value="status.start" />
                    </el-select>
                </el-form-item>
                <el-form-item label="目的地" :label-width="formLabelWidth">
                    <el-select v-model="form.end" placeholder="目的地" clearable>
                        <el-option v-for="status in endList" :key="status.id" :label="status.end"
                            :value="status.end" />
                    </el-select>
                </el-form-item>
                <el-form-item label="类型" :label-width="formLabelWidth">
                    <el-select v-model="form.type" placeholder="车辆状态" clearable>
                        <el-option v-for="status in TripStatus" :key="status.code" :label="status.label"
                            :value="status.code" />
                    </el-select>
                </el-form-item>
                <el-form-item label="价格" :label-width="formLabelWidth">
                    <el-input v-model="form.price" autocomplete="off" />
                </el-form-item>
                <el-form-item label="车辆数量" :label-width="formLabelWidth">
                    <el-input v-model="form.vehiclesNumber" autocomplete="off" />
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer">
                <el-button @click="cancelForm" type="info">取消</el-button>
                <el-button type="primary" :loading="loading" @click="onClick">
                    {{ loading ? '提交中 ...' : '更改' }}
                </el-button>
            </div>
        </div>
    </el-drawer>

    <el-drawer v-model="table" title="添加行程" direction="rtl" class="demo-drawer">
        <div class="demo-drawer__content">
            <el-form :model="form_add">
                <el-form-item label="行程编号" :label-width="formLabelWidth">
                    <el-input v-model="form_add.tripNumber" autocomplete="off" />
                </el-form-item>
                <el-form-item label="起始地" :label-width="formLabelWidth">
                    <el-select v-model="form_add.start" placeholder="起始地" clearable>
                        <el-option v-for="status in StartList" :key="status.id" :label="status.start"
                            :value="status.start" />
                    </el-select>
                </el-form-item>
                <el-form-item label="目的地" :label-width="formLabelWidth">
                    <el-select v-model="form_add.end" placeholder="目的地" clearable>
                        <el-option v-for="status in endList" :key="status.id" :label="status.end"
                            :value="status.end" />
                    </el-select>
                </el-form-item>
                <el-form-item label="类型" :label-width="formLabelWidth">
                    <el-select v-model="form_add.type" placeholder="车辆状态" clearable>
                        <el-option v-for="status in TripStatus" :key="status.code" :label="status.label"
                            :value="status.code" />
                    </el-select>
                </el-form-item>
                <el-form-item label="价格" :label-width="formLabelWidth">
                    <el-input v-model="form_add.price" autocomplete="off" />
                </el-form-item>
                <el-form-item label="车辆数量" :label-width="formLabelWidth">
                    <el-input v-model="form_add.vehiclesNumber" autocomplete="off" />
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer">
                <el-button @click="cancelForm" type="info">取消</el-button>
                <el-button type="primary" :loading="loading" @click="onClicks">
                    {{ loading ? '添加中 ...' : '添加' }}
                </el-button>
            </div>
        </div>
    </el-drawer>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { Edit, Delete } from '@element-plus/icons-vue'
import { TripList, TripListById, updateTrip, deleteTrip, addTripList, GetStart, GetEnd } from '../api/trip.js'
import { ElMessage, ElMessageBox } from 'element-plus';
import { TripStatus } from '../utils/status'
import { useRouter } from 'vue-router';

const router = useRouter();

const form = reactive({
    tripNumber: '',
    start: '',
    end: '',
    price: '',
    vehiclesNumber: '',
    type: '',
})

const form_add = reactive({
    tripNumber: '',
    start: '',
    end: '',
    price: '',
    vehiclesNumber: '',
    type: '',
})

const reset = ()=>{
    form_add.tripNumber = '',
    form_add.start = '',
    form_add.end = '',
    form_add.price = '',
    form_add.vehiclesNumber = '',
    form_add.type = ''
}

const table = ref(false)
const dialog = ref(false)
const loading = ref(false)

const formLabelWidth = '80px'

const onClick = async () => {
    try {
        const result = await updateTrip(form);
        if (result.data.code === 200) {
            ElMessage.success(result.data.msg ? result.data.msg : '修改成功')
            loading.value = true
            setTimeout(() => {
                loading.value = false
                dialog.value = false
            }, 400);
            GetTripList()
        } else {
            ElMessage.error('修改失败，请检查修改信息是否符合规范')
        }
    } catch (error) {
        ElMessage.error('修改失败，请检查修改信息是否符合规范')
    }
    dialog.value = false
}

const onClicks = async () => {
    console.log("form_add", form_add)
    try {
        const result = await addTripList(form_add);
        if (result.data.code === 200) {
            ElMessage.success('添加成功');
            // router.push('/journey')
            reset();
            GetTripList()
        }
    } catch (error) {
        ElMessage.error('添加失败')
        reset();
    }
    table.value = false
}

const searchForm = reactive({
    tripNumber: '',
    start: '',
    end: '',
})

const cancelForm = () => {
    loading.value = false
    dialog.value = false
}

const currentPage4 = ref(1)
const pageSize4 = ref(12)
const total = ref(0)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
    pageSize4.value = val;
    GetTripList();
};

const handleCurrentChange = (val: number) => {
    currentPage4.value = val;
    GetTripList();
};

const tableData = ref([])

const GetTripList = async () => {
    const payload = {
        page: currentPage4.value,
        pageSize: pageSize4.value,
        tripNumber: searchForm.tripNumber,
        start: searchForm.start,
        end: searchForm.end,
    };
    console.log(payload)
    try {
        const result = await TripList(payload)
        if (result.data.code === 200) {
            total.value = result.data.data.total;
            tableData.value = result.data.data.recodes;
            ElMessage.success('行程列表')
        }
    } catch (error) {
        ElMessage.error('无法获取')
    }
}

const updateTripList = async (id: number) => {
    dialog.value = true
    console.log(id)
    try {
        const result = await TripListById(id);
        if (result.data.code === 200) {
            const data = result.data.data[0];
            Object.assign(form, data)
        }
    } catch (error) {
        ElMessage.error('无法回显路程信息')
    }
}

const deleteTripList = (id: number) => {
    ElMessageBox.confirm(
        '确定删除该路程信息?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const result = await deleteTrip(id);
            if (result.data.code === 200) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                });
                GetTripList()
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

const addTrip = () => {
    table.value = true
}

const StartList = ref([])
const endList = ref([])

const Start = async()=>{
    try{
        const result = await GetStart();
        console.log(result.data.data)
        if(result.data.code === 200){
            StartList.value = result.data.data;
        }
    }catch(error){
        console.log('无法获取')
    }
}

const End = async()=>{
    try{
        const result = await GetEnd();
        console.log(result.data.data)
        if(result.data.code === 200){
            endList.value = result.data.data;
        }
    }catch(error){
        console.log('无法获取')
    }
}

onMounted(() => {
    GetTripList(),
    Start(),
    End()
})

const statusColorMap = {
    1: '#4caf50',  // Example status color
    0: '#ff9800',  // Example status color
    2: '#f44336',  // Example status color
    // Add more status colors here
}

const getStatusLabel = (type: number) => {
    const statusItem = TripStatus.value.find(item => item.code === type);
    const color = statusColorMap[type] || '#000'  // Default to black if status not found
    return { label: statusItem ? statusItem.label : '未知', color }
}
</script>

<style scoped>
.demo-form-inline .el-input {
    width: 200px;
}

.demo-form-inline .el-select {
    width: 200px;
}

.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

.type-status-class {
    color: #fff;
    padding: 3px 8px;
    border-radius: 10px;
    display: inline-block;
    width: 60px;
    text-align: center;
}
</style>